package com.zzg.lucene;

import java.io.IOException;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.IntPoint;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.SortField;
import org.apache.lucene.search.TopFieldDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;

public class LuceneIntPoint {

	public void addIntPoint(Document document, String name, int value) {
		Field field = new IntPoint(name, value);
		document.add(field);
		// 要排序，必须添加一个同名的NumericDocValuesField
		field = new NumericDocValuesField(name, value);
		document.add(field);
		// 要存储值，必须添加一个同名的StoredField
		field = new StoredField(name, value);
		document.add(field);
	}

	public static void main(String[] args) throws IOException {
		LuceneIntPoint intPoint = new LuceneIntPoint();

		Document document = new Document();
		Directory directory = new RAMDirectory();
		IndexWriter indexWriter = new IndexWriter(directory, new IndexWriterConfig(new StandardAnalyzer()));
		intPoint.addIntPoint(document, "intValue", 10);
		indexWriter.addDocument(document);
		document = new Document();
		intPoint.addIntPoint(document, "intValue", 20);
		indexWriter.addDocument(document);
		document = new Document();
		intPoint.addIntPoint(document, "intValue", 30);
		indexWriter.addDocument(document);
		indexWriter.close();

		IndexSearcher indexSearcher = new IndexSearcher(DirectoryReader.open(directory));
		// 第三个参数为true，表示从大到小
		SortField intValues = new SortField("intValue", SortField.Type.INT, true);
		TopFieldDocs search = indexSearcher.search(new MatchAllDocsQuery(), 10, new Sort(intValues));
		ScoreDoc[] scoreDocs = search.scoreDocs;
		for (ScoreDoc scoreDoc : scoreDocs) {
			System.out.println(indexSearcher.doc(scoreDoc.doc));
		}
	}

}
